package com.ysz.client.task;

import com.ysz.common.struct.ClientStruct;
import com.ysz.common.util.TimeUtil;
import com.ysz.server.conn.ServerConn;
import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;

import java.time.LocalDateTime;
import java.util.Objects;


/**
 * @ClassName ClientTask
 * @Description TODO
 * @Data 15:02
 * @Version 1.0
 * @Author ysz
 */
public class ClientTask implements Runnable {

    private String ip;

    public ClientTask(String ip) {
        this.ip = ip;
    }


    @SneakyThrows
    @Override
    public void run() {
        LocalDateTime beforeSendTime = null;
        LocalDateTime beforeNextSendTime = null;
        while (true) {
            ClientStruct clientStruct = new ClientStruct();
            clientStruct.setIp(this.ip);
            clientStruct.setSendTime(LocalDateTime.now());
            if (Objects.nonNull(beforeSendTime)) {
                clientStruct.setBeforeSendTime(beforeSendTime);
            }
            beforeSendTime = clientStruct.getSendTime();
            ServerConn serverConn = new ServerConn();
            serverConn.accept(clientStruct);
            System.out.println("=========================================");
            System.out.println("客户端的ip：" + clientStruct.getIp());
            System.out.println("客户端上一次发送请求的时间：" + clientStruct.getBeforeSendTime());
            System.out.println("客户端发送请求的时间：" + clientStruct.getSendTime());
            System.out.println("客户端下一次发送请求的时间：" + clientStruct.getNextSendTime());
            if (Objects.nonNull(beforeNextSendTime)) {
                boolean after = clientStruct.getSendTime().isAfter(beforeNextSendTime);
                System.out.println("客户端是否超时：" + (after ? "是" : "否"));
            } else {
                System.out.println("客户端是否超时：否");
            }
            beforeNextSendTime = clientStruct.getNextSendTime();
            System.out.println("=========================================");
            //模拟客户端发送心跳包  可能在规定时间之前发出  也可能在规定时间后发出
            int i = RandomUtils.nextInt(0, TimeUtil.parseLocalDateTime(clientStruct.getNextSendTime()) + 20);
            Thread.sleep(i * 1000);
        }
    }
}
